<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 class="title">用户注册</h2>
      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="registerRules"
        label-position="top"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="registerForm.nickName"
            placeholder="昵称长度不能小于2位"
            clearable
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="用户名长度为4-15位"
            clearable
            prefix-icon="Avatar"
          />
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input
            v-model="registerForm.userPwd"
            type="password"
            placeholder="用户密码为为6-15位"
            show-password
            prefix-icon="Lock"
          />
          <password-strength :password="registerForm.userPwd" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
            prefix-icon="Lock"
          />
        </el-form-item>
        <el-button
          type="primary"
          size="large"
          class="register-btn"
          :loading="loading"
          native-type="submit"
        >
          立即注册
        </el-button>
        <div class="login-link">
          已有账号？<el-link type="primary" @click="goLogin">去登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { registerValidate, registerApi } from '@/api/index'
import PasswordStrength from '@/components/PasswordStrength.vue'

const router = useRouter()
const formRef = ref()
// 表单数据
const registerForm = ref({
  username: "",
  userPwd: "",
  confirmPassword: "",
  nickName:""
})


const registerRules = {
  nickName:[
    {required: true, message: '昵称不能为空', trigger: 'blur'},
    {min: 2, message: '昵称长度不能小于2位', trigger: 'blur'}
  ],
  username:[
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {min: 4, max: 15, message: '用户名长度为4-15位', trigger: 'blur'}
  ],
  userPwd:[
    {required: true, message: '用户密码不能为空', trigger: 'blur'},
    {min: 6, max: 15, message: '用户密码为为6-15位', trigger: 'blur'}
  ],
  confirmPassword:[{
    required: true,
    trigger: ['blur','input'],
    validator: (rule, value, callback) =>{
      if(!value){
        callback(new Error('请再次输入密码'))
      }else if(value !== registerForm.value?.userPwd){
        callback(new Error('你输入的密码不一致'))
      }else{
        callback()
      }
    }
  }]
}
// 注册逻辑
const loading = ref(false)
//注册接口
const handleRegister = async() => {
  //输入框值的规则校验
  if(!formRef.value){
    return
  }
  const isValid = await new Promise(
    (resolve)=>{
       formRef.value.validate(
        (valid)=>{
          resolve(valid)
        }
      ) 
    }
  )
  try{
    loading.value = true
    if(isValid){
      //校验用户名是否可用？
      await registerValidate(registerForm.value.username)

      //定义一个user对象
      const userObj = {
        username: "",
        userPwd: "",
        nickName: ""
      }
      userObj.username = registerForm.value.username
      userObj.userPwd = registerForm.value.userPwd
      userObj.nickName = registerForm.value.nickName
      //调用注册接口
      await registerApi(userObj)
      //清空registerForm数据
      formRef.value?.resetFields()
      ElMessage.success("注册成功，5秒后跳转到登录界面！")
      setTimeout(()=>{goLogin()},5000)
     }else{
      console.log("校验失败")
    }
  }finally{
    loading.value = false
  }
}
// 跳转登录
const goLogin = () => {
  router.push({name:"Login"})
  //router.push({path:"/login"})
}
</script>

<style lang="less" scoped>
.register-container {
  min-height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
  //background: linear-gradient(135deg, #f0f2f5 0%, #e6e9ef 100%);
  background: linear-gradient(135deg, #f8f8f9 0%, #f7f8f8 100%);


  .register-card {
    width: 480px;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);

    .title {
      text-align: center;
      margin-bottom: 30px;
      color: #303133;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      padding-bottom: 8px;
    }

    .register-btn {
      width: 100%;
      margin-top: 20px;
      letter-spacing: 2px;
    }

    .login-link {
      text-align: center;
      margin-top: 20px;
      color: #606266;

      .el-link {
        vertical-align: baseline;
      }
    }
  }
}
</style>